package com.dly.hope.scheduled;

import com.dly.hope.constant.RedisConstant;
import com.dly.hope.dao.UserAccountDao;
import com.dly.hope.dto.UserSocketDto;
import com.dly.hope.model.vo.OnlineShowVo;
import com.dly.hope.modle.UserAccount;
import com.dly.hope.type.MessageType;
import com.dly.hope.type.RoleType;
import com.dly.hope.utils.JsonFormatUtil;
import com.dly.hope.utils.RedisUtil;
import com.dly.hope.webSocket.WebSocketDto;
import com.dly.hope.webSocket.WebSocketServer;
import com.dly.hope.webSocket.dto.MessageDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.SimpleTimeZone;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;


@Component
@Slf4j
public class ScheduledService {

    @Resource
    private RedisLockRegistry redisLockRegistry;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserAccountDao userAccountDao;



    private static final String locKey = "onlinePush";

    @Scheduled(cron = "0/10 * * * * *")
    public void scheduled(){

        Lock lock = redisLockRegistry.obtain(locKey);

        try {
            //尝试两秒获取锁
            boolean b = lock.tryLock(2, TimeUnit.SECONDS);
            if(b){
                sendOnline();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private void sendOnline(){


        int size = redisUtil.getOnline(RedisConstant.ONLINE).size();
        if(size == 0){
            return;
        }

        //获取超级管理员的id
        List<UserAccount> superAccount = userAccountDao.getSuperAccount(RoleType.SUPER_ADMIN);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        OnlineShowVo onlineShowVo = new OnlineShowVo();
        onlineShowVo.setDate(format);
        onlineShowVo.setCount(size);

        superAccount.forEach(user->{
            UserSocketDto accept = new UserSocketDto();
            accept.setName(user.getAccountName());
            accept.setUserId(user.getId());
            MessageDto messageDto = new MessageDto();

            messageDto.setMessage(JsonFormatUtil.writeToJson(onlineShowVo));

            messageDto.setType(MessageType.ONLINESHOW);
            messageDto.setAcceptUserSocketDto(accept);
            WebSocketServer.sendMessage(JsonFormatUtil.writeToJson(messageDto), accept.getUserId());
        });

    }
}
